/*
 * MegaMek - Copyright (C) 2000,2001,2002,2003,2004 Ben Mazur (bmazur@sev.org)
 *
 *  This program is free software; you can redistribute it and/or modify it
 *  under the terms of the GNU General Public License as published by the Free
 *  Software Foundation; either version 2 of the License, or (at your option)
 *  any later version.
 *
 *  This program is distributed in the hope that it will be useful, but
 *  WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
 *  or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
 *  for more details.
 */

package megamek.common.actions;

import megamek.common.BipedMech;
import megamek.common.Compute;
import megamek.common.Entity;
import megamek.common.IGame;
import megamek.common.IHex;
import megamek.common.Mech;
import megamek.common.Mounted;
import megamek.common.Player;
import megamek.common.Protomech;
import megamek.common.TargetRoll;
import megamek.common.Targetable;
import megamek.common.ToHitData;

// TODO: Auto-generated Javadoc
/**
 * The attacker grapples the target.
 */
public class GrappleAttackAction extends PhysicalAttackAction {

    /** The Constant serialVersionUID. */
    private static final long serialVersionUID = -4178252788550426489L;

    /**
     * Instantiates a new grapple attack action.
     *
     * @param entityId the entity id
     * @param targetId the target id
     */
    public GrappleAttackAction(int entityId, int targetId) {
        super(entityId, targetId);
    }

    /**
     * Instantiates a new grapple attack action.
     *
     * @param entityId the entity id
     * @param targetType the target type
     * @param targetId the target id
     */
    public GrappleAttackAction(int entityId, int targetType, int targetId) {
        super(entityId, targetType, targetId);
    }

    /**
     * To hit.
     *
     * @param game the game
     * @return the to hit data
     */
    public ToHitData toHit(IGame game) {
        return toHit(game, getEntityId(), game.getTarget(getTargetType(), getTargetId()));
    }

    /**
     * To-hit number.
     *
     * @param game the game
     * @param attackerId the attacker id
     * @param target the target
     * @return the to hit data
     */
    public static ToHitData toHit(IGame game, int attackerId, Targetable target) {
        return toHit(game,attackerId,target,Entity.GRAPPLE_BOTH);
    }

    /**
     * To hit.
     *
     * @param game the game
     * @param attackerId the attacker id
     * @param target the target
     * @param grappleSide the grapple side
     * @return the to hit data
     */
    public static ToHitData toHit(IGame game, int attackerId, Targetable target, int grappleSide) {
        final Entity attackEntity = game.getEntity(attackerId);
        if (attackEntity == null)
            return new ToHitData(TargetRoll.IMPOSSIBLE, "You can't attack from a null entity!");

        if (!game.getOptions().booleanOption("tacops_grappling"))
            return new ToHitData(TargetRoll.IMPOSSIBLE, "grappling attack not allowed");

        String impossible = toHitIsImpossible(game, attackEntity, target);
        if (impossible != null && !impossible.equals("Locked in Grapple")) {
            return new ToHitData(TargetRoll.IMPOSSIBLE, "impossible");
        }

        if (!game.getOptions().booleanOption("friendly_fire")) {
            // a friendly unit can never be the target of a direct attack.
            if (target.getTargetType() == Targetable.TYPE_ENTITY
                    && (((Entity)target).getOwnerId() == attackEntity.getOwnerId()
                            || (((Entity)target).getOwner().getTeam() != Player.TEAM_NONE
                                    && attackEntity.getOwner().getTeam() != Player.TEAM_NONE
                                    && attackEntity.getOwner().getTeam() == ((Entity)target).getOwner().getTeam())))
                return new ToHitData(TargetRoll.IMPOSSIBLE, "A friendly unit can never be the target of a direct attack.");
        }

        IHex attHex = game.getBoard().getHex(attackEntity.getPosition());
        IHex targHex = game.getBoard().getHex(target.getPosition());
        final int attackerElevation = attackEntity.getElevation() + attHex.getElevation();
        // final int attackerHeight = attackerElevation + ae.getHeight();
        final int targetElevation = target.getElevation() + targHex.getElevation();
        // final int targetHeight = targetElevation + target.getHeight();
        ToHitData toHit;

        // non-mechs can't grapple or be grappled
        if ((!(attackEntity instanceof BipedMech) && !(attackEntity instanceof Protomech)) || (!(target instanceof Mech) && !(target instanceof Protomech))) {
            return new ToHitData(TargetRoll.IMPOSSIBLE, "Only biped mechs can grapple 'Mechs and Protomechs");
        }

        Entity targetEntity = (Entity) target;
        final boolean counter = attackEntity.getGrappled() != Entity.NONE && !attackEntity.isGrappleAttacker();

        // requires 2 good arms
        if (grappleSide == Entity.GRAPPLE_BOTH ) {

            if ( attackEntity.isLocationBad(Mech.LOC_LARM) || attackEntity.isLocationBad(Mech.LOC_RARM) ) {
                return new ToHitData(TargetRoll.IMPOSSIBLE, "Arm missing");
            }

            if (!attackEntity.hasWorkingSystem(Mech.ACTUATOR_SHOULDER, Mech.LOC_RARM)
                    || !attackEntity.hasWorkingSystem(Mech.ACTUATOR_SHOULDER, Mech.LOC_LARM)) {
                return new ToHitData(TargetRoll.IMPOSSIBLE, "Shoulder missing/destroyed");
            }
        }else if ( grappleSide == Entity.GRAPPLE_LEFT ) {
            if ( attackEntity.isLocationBad(Mech.LOC_LARM) ) {
                return new ToHitData(TargetRoll.IMPOSSIBLE, "Arm missing");
            }

            if (!attackEntity.hasWorkingSystem(Mech.ACTUATOR_SHOULDER, Mech.LOC_LARM)) {
                return new ToHitData(TargetRoll.IMPOSSIBLE, "Shoulder missing/destroyed");
            }
        } else {
            if ( attackEntity.isLocationBad(Mech.LOC_RARM) ) {
                return new ToHitData(TargetRoll.IMPOSSIBLE, "Arm missing");
            }

            if (!attackEntity.hasWorkingSystem(Mech.ACTUATOR_SHOULDER, Mech.LOC_RARM)) {
                return new ToHitData(TargetRoll.IMPOSSIBLE, "Shoulder missing/destroyed");
            }
        }


        // check range
        final int range = attackEntity.getPosition().distance(target.getPosition());
        if (range != 1 && !counter) {
            return new ToHitData(TargetRoll.IMPOSSIBLE, "Target not in range");
        }

        // check elevation (attacker must be able to enter target hex)
        if (Math.abs(attackerElevation - targetElevation) > attackEntity.getMaxElevationChange()) {
            return new ToHitData(TargetRoll.IMPOSSIBLE, "Target elevation not in range");
        }

        // check facing
        if (!counter && !Compute.isInArc(attackEntity.getPosition(), attackEntity.getFacing(), target.getPosition(), Compute.ARC_FORWARD)) {
            return new ToHitData(TargetRoll.IMPOSSIBLE, "Target not in arc");
        }

        // can't grapple while prone
        if (attackEntity.isProne()) {
            return new ToHitData(TargetRoll.IMPOSSIBLE, "Attacker is prone");
        }
        if (((Entity) target).isProne()) {
            return new ToHitData(TargetRoll.IMPOSSIBLE, "Target is prone");
        }

        // check if attacker has fired any weapons
        if (!counter) {
            for (Mounted mounted : attackEntity.getWeaponList()) {
                if (mounted.isUsedThisRound()) {
                    return new ToHitData(TargetRoll.IMPOSSIBLE, "Fired weapons");
                }
            }
        }

        // already done?
        int atGr = attackEntity.getGrappled();
        int deGr = targetEntity.getGrappled();
        if ((atGr != Entity.NONE || deGr != Entity.NONE) && atGr != target.getTargetId() && targetEntity.isGrappleAttacker()) {
            return new ToHitData(TargetRoll.IMPOSSIBLE, "Already grappled");
        }

        // Set the base BTH
        int base = attackEntity.getCrew().getPiloting();

        // Start the To-Hit
        toHit = new ToHitData(base, "base");

        setCommonModifiers(toHit, game, attackEntity, target);

        if (attackEntity instanceof Mech && grappleSide == Entity.GRAPPLE_BOTH ) {
            grappleBothSides(attackEntity, toHit);

        } else if (attackEntity instanceof Mech && grappleSide == Entity.GRAPPLE_RIGHT ) {
            grappleRightSide(attackEntity, toHit);

        } else {
            grapleLeftSide(attackEntity, toHit);

        }

        if ( grappleSide != Entity.GRAPPLE_BOTH && attackEntity instanceof Mech ) {
            Mech attacker = (Mech)attackEntity;

            if ( attacker.hasTSM() && attacker.heat >= 9
                    && ( !(targetEntity instanceof Mech) || !((Mech)targetEntity).hasTSM() || (((Mech)targetEntity).hasTSM() && targetEntity.heat < 9))) {
                toHit.addModifier(-2, "TSM Active Bonus");
            }
        }

        // Weight class difference
        checkWeight(attackEntity, toHit, targetEntity);
        // done!
        return toHit;
    }

	/**
	 * Graple left side.
	 *
	 * @param attackEntity the attack entity
	 * @param toHit the to hit
	 */
	private static void grapleLeftSide(final Entity attackEntity,
			ToHitData toHit) {
		// damaged or missing actuators
		if (!attackEntity.hasWorkingSystem(Mech.ACTUATOR_UPPER_ARM, Mech.LOC_LARM)) {
		    toHit.addModifier(2, "Left upper arm actuator destroyed");
		}
		if (!attackEntity.hasWorkingSystem(Mech.ACTUATOR_LOWER_ARM, Mech.LOC_LARM)) {
		    toHit.addModifier(2, "Left lower arm actuator destroyed");
		}
		if (!attackEntity.hasWorkingSystem(Mech.ACTUATOR_HAND, Mech.LOC_LARM)) {
		    toHit.addModifier(1, "Left hand actuator destroyed");
		}
		if ( attackEntity.hasFunctionalArmAES(Mech.LOC_LARM) ) {
		    toHit.addModifier(-1,"AES modifer");
		}
	}

	/**
	 * Grapple right side.
	 *
	 * @param attackEntity the attack entity
	 * @param toHit the to hit
	 */
	private static void grappleRightSide(final Entity attackEntity,
			ToHitData toHit) {
		// damaged or missing actuators
		if (!attackEntity.hasWorkingSystem(Mech.ACTUATOR_UPPER_ARM, Mech.LOC_RARM)) {
		    toHit.addModifier(2, "Right upper arm actuator destroyed");
		}
		if (!attackEntity.hasWorkingSystem(Mech.ACTUATOR_LOWER_ARM, Mech.LOC_RARM)) {
		    toHit.addModifier(2, "Right lower arm actuator destroyed");
		}
		if (!attackEntity.hasWorkingSystem(Mech.ACTUATOR_HAND, Mech.LOC_RARM)) {
		    toHit.addModifier(1, "Right hand actuator destroyed");
		}
		if ( attackEntity.hasFunctionalArmAES(Mech.LOC_RARM)) {
		    toHit.addModifier(-1,"AES modifer");
		}
	}

	/**
	 * Grapple both sides.
	 *
	 * @param attackEntity the attack entity
	 * @param toHit the to hit
	 */
	private static void grappleBothSides(final Entity attackEntity,
			ToHitData toHit) {
		// damaged or missing actuators
		if (!attackEntity.hasWorkingSystem(Mech.ACTUATOR_UPPER_ARM, Mech.LOC_LARM)) {
		    toHit.addModifier(2, "Left upper arm actuator destroyed");
		}
		if (!attackEntity.hasWorkingSystem(Mech.ACTUATOR_LOWER_ARM, Mech.LOC_LARM)) {
		    toHit.addModifier(2, "Left lower arm actuator destroyed");
		}
		if (!attackEntity.hasWorkingSystem(Mech.ACTUATOR_HAND, Mech.LOC_LARM)) {
		    toHit.addModifier(1, "Left hand actuator destroyed");
		}

		if (!attackEntity.hasWorkingSystem(Mech.ACTUATOR_UPPER_ARM, Mech.LOC_RARM)) {
		    toHit.addModifier(2, "Right upper arm actuator destroyed");
		}
		if (!attackEntity.hasWorkingSystem(Mech.ACTUATOR_LOWER_ARM, Mech.LOC_RARM)) {
		    toHit.addModifier(2, "Right lower arm actuator destroyed");
		}
		if (!attackEntity.hasWorkingSystem(Mech.ACTUATOR_HAND, Mech.LOC_RARM)) {
		    toHit.addModifier(1, "Right hand actuator destroyed");
		}

		if ( attackEntity.hasFunctionalArmAES(Mech.LOC_RARM) && attackEntity.hasFunctionalArmAES(Mech.LOC_LARM) ) {
		    toHit.addModifier(-1,"AES modifer");
		}
	}

	/**
	 * Check weight.
	 *
	 * @param attackEntity the attack entity
	 * @param toHit the to hit
	 * @param te the te
	 */
	private static void checkWeight(final Entity attackEntity, ToHitData toHit,
			Entity te) {
		int wmod = te.getWeightClass() - attackEntity.getWeightClass();

        if (te instanceof Protomech && !(attackEntity instanceof Protomech)) {
            wmod = attackEntity.getWeightClass() * -1;
        } else if (attackEntity instanceof Protomech && !(te instanceof Protomech)) {
            wmod = te.getWeightClass();
        } else if (te instanceof Protomech && attackEntity instanceof Protomech) {
            wmod = 0;
        }

        if (wmod != 0) {
            toHit.addModifier(wmod, "Weight class difference");
        }
	}

}
